package com.alstudio.utils.android.net.http;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;

import android.text.TextUtils;

import com.alstudio.utils.android.ALFileManager;
import com.alstudio.utils.android.net.http.http2.HttpUploadRequest;
import com.alstudio.utils.android.net.http.http2.IHttpProgressHandler;
import com.alstudio.utils.formater.FileIdUtils;
import com.alstudio.utils.log.ALLog;

public class UploadPhotoRequest {

	public static final String TAG = UploadPhotoRequest.class.getSimpleName();

	public static final int STATUS_OK = 200; // 成功
	public static final int ERROR_UNKNOW = -1; // 未知错误
	public static final int ERROR_NET_EXCEPTION = -2; // 网络异常
	public static final int ERROR_FILE_NOT_EXIST = -3; // 文件不存在
	public static final int ERROR_FILE_INVALID = -4; // 非法文件名或内容

	private HttpUploadRequest httpRequest = null;

	private String username;
	private String filepath;
	private String url;

	public UploadPhotoRequest(String servletUrl, String token, String username,
			String filepath) {
		if (TextUtils.isEmpty(servletUrl) || TextUtils.isEmpty(filepath)) {

			ALLog.d(String.format("参数不对: url(%s) , filePath(%s)",
					servletUrl, token, filepath));
			throw new IllegalArgumentException();
		}

		this.username = username;
		this.filepath = filepath;

		initReqeust(servletUrl, token, username, filepath);
	}

	public String getUserId() {
		return username;
	}

	public String getFilepath() {
		return filepath;
	}

	private void initReqeust(String servletUrl, String token, String username,
			String filepath) {
		String fileName = "";
		try {
			fileName = URLEncoder.encode(ALFileManager.getFileName(filepath),
					"UTF-8");
		} catch (UnsupportedEncodingException e) {
			fileName = "";
		}

		String params;
		if (TextUtils.isEmpty(username)) {
			params = String.format("?type=upload&filename=%s", fileName);
		} else {
			params = String.format("?type=upload&username=%s&filename=%s",
					username, fileName);
		}

		url = TextUtils.isEmpty(params) ? servletUrl : servletUrl + params;

		httpRequest = new HttpUploadRequest(url, filepath);
		httpRequest.addHeader("token", token);
	}

	public void request(final Callback callback) {
		httpRequest.request(new HttpHandler(callback), false);
	}

	public void requestAsync(Callback callback) {
		httpRequest.requestAsync(new HttpHandler(callback), false);
	}

	private class HttpHandler implements IHttpProgressHandler {

		public Callback callback;

		public HttpHandler(Callback callback) {
			this.callback = callback;
		}

		@Override
		public void handleResponse(HttpResponse response) throws IOException {
			int status = response.getStatusLine().getStatusCode();
			if (status == HttpStatus.SC_OK) {
				Header header;

				header = response.getFirstHeader("largeurl");
				String pictureFileId;
				if (header != null) {
					pictureFileId = FileIdUtils
							.getBareFileId(header.getValue());

				} else {
					pictureFileId = "";
				}

				header = response.getFirstHeader("smallurl");
				String thumbFileId;
				if (header != null) {
					thumbFileId = FileIdUtils.getBareFileId(header.getValue());

				} else {
					thumbFileId = "";
				}

				ALLog.d(String.format(
						"上传文件完成 : picture(%s) thumb(%s), url = %s",
						pictureFileId, thumbFileId, url));

				if (callback != null) {
					if (TextUtils.isEmpty(pictureFileId)
							|| TextUtils.isEmpty(thumbFileId)) {
						callback.onFailed(UploadPhotoRequest.this, ERROR_UNKNOW);
					} else {
						callback.onSuccess(UploadPhotoRequest.this,
								pictureFileId, thumbFileId);
					}
				}

			} else {
				ALLog.e(String.format(
						"上传文件失败 : status = %s, url = %s", status, url));

				if (callback != null)
					callback.onFailed(UploadPhotoRequest.this,
							ERROR_NET_EXCEPTION);

			}

		}

		@Override
		public void handleProgress(long transferred, long fileSize) {

		}

		@Override
		public void handleInterrupted() {
			if (callback != null)
				callback.onCancelled(UploadPhotoRequest.this);
		}

		@Override
		public void handleException(Exception e) {
			if (callback != null) {
				if (e instanceof FileNotFoundException) {
					callback.onFailed(UploadPhotoRequest.this,
							ERROR_FILE_NOT_EXIST);

				} else {
					callback.onFailed(UploadPhotoRequest.this,
							ERROR_NET_EXCEPTION);

				}
			}

		}

	}

	public static interface Callback {
		public void onSuccess(UploadPhotoRequest sender, String pictureFileId,
				String thumbFileId);

		public void onFailed(UploadPhotoRequest sender, int errCode);

		public void onCancelled(UploadPhotoRequest sender);
	}
}
